import {equalAry} from '@/utils/ary.js'
export default{
	namespaced:true,
	state:{
		shopcartList:JSON.parse(uni.getStorageSync('shopcart')||'[]')
	},
	mutations:{
		addToShopcartSync(state,payload){
			console.log('--------加入到购物车的同步方法------------');
			console.log('payload',payload);
			const result=state.shopcartList.find(item=>{
				if(item.gid==payload.gid){
					item.params.sort()
					payload.params.sort()
					if(equalAry(item.params,payload.params)){
						return true
					}
				}else{
					return false
				}
			})
			if(!result){
				//添加购物车信息对象
				state.shopcartList.push(payload)
			}else{
				result.count+=payload.count
			}
			uni.setStorageSync('shopcart',JSON.stringify(state.shopcartList))
		},
		updateShopcartCount(state,payload){
			console.log('---------更新购物车数量---------------');
			const result=state.shopcartList.find(item=>{
				if(item.gid==payload.gid){
					item.params.sort()
					payload.params.sort()
					if(equalAry(item.params,payload.params)){
						return true
					}
				}else{
					return false
				}
			})
			if(result){
				result.count=payload.count
				//使用Promise来保证顺序
				Promise.resolve().then(()=>{
					uni.setStorageSync("shopcart",JSON.stringify(state.shopcartList))
				})
			}
		},
		updateShopcartCheckStatus(state,payload){
			console.log('---------更新购物商品状态---------------');
			const result=state.shopcartList.find(item=>{
				if(item.gid==payload.gid){
					item.params.sort()
					payload.params.sort()
					if(equalAry(item.params,payload.params)){
						return true
					}
				}else{
					return false
				}
			})
			if(result){
				result.checked=!payload.checked
				Promise.resolve().then(()=>{
					uni.setStorageSync("shopcart",JSON.stringify(state.shopcartList))
				})
			}
		},
		removeShopcart(state,payload){
			console.log('---------删除商品信息---------------');
			let idx=0
			state.shopcartList.forEach((item,index)=>{
				if(item.gid==payload.gid){
					item.params.sort()
					payload.params.sort()
					if(equalAry(item.params,payload.params)){
						idx=index
					}
				}
			})
			state.shopcartList.splice(idx,1)
			Promise.resolve().then(()=>{
				uni.setStorageSync("shopcart",JSON.stringify(state.shopcartList))
			})
		}
	},

	getters:{
		shopcartLen(state){
			return state.shopcartList.length
		},
		totalPrice(state){
			return state.shopcartList.filter(item=>item.checked).reduce((prev,cur)=>prev+cur.price*cur.count,0)
		}
	}
}